<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="googlead9dc5c68da2c41a" />








  <meta name="baidu-site-verification" content="baV2kbPkNW" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/favicon.ico?v=5.1.4" color="#222">





  <meta name="keywords" content="机器学习,林轩田,笔记,技法," />





  <link rel="alternate" href="/atom.xml" title="红色石头的机器学习之路" type="application/atom+xml" />






<meta name="keywords" content="机器学习,林轩田,笔记,技法">
<meta property="og:type" content="article">
<meta property="og:title" content="台湾大学林轩田机器学习技法课程学习笔记9 -- Decision Tree">
<meta property="og:url" content="https://redstonewill.github.io/2018/03/18/26/index.html">
<meta property="og:site_name" content="红色石头的机器学习之路">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://img.blog.csdn.net/20170719082956412?imageView/2/w/500/q/100">
<meta property="og:image" content="http://img.blog.csdn.net/20170719082956412?">
<meta property="og:image" content="http://img.blog.csdn.net/20170719084744044?">
<meta property="og:image" content="http://img.blog.csdn.net/20170719103654190?">
<meta property="og:image" content="http://img.blog.csdn.net/20170719103835724?">
<meta property="og:image" content="http://img.blog.csdn.net/20170719155104812?">
<meta property="og:image" content="http://img.blog.csdn.net/20170720073120706?">
<meta property="og:image" content="http://img.blog.csdn.net/20170720074057776?">
<meta property="og:image" content="http://img.blog.csdn.net/20170720081326313?">
<meta property="og:image" content="http://img.blog.csdn.net/20170720083357302?">
<meta property="og:image" content="http://img.blog.csdn.net/20170720090259338?">
<meta property="og:image" content="http://img.blog.csdn.net/20170720112908397?">
<meta property="og:image" content="http://img.blog.csdn.net/20170720135537933?">
<meta property="og:image" content="http://img.blog.csdn.net/20170720152355327?">
<meta property="og:image" content="http://img.blog.csdn.net/20170721083658001?">
<meta property="og:image" content="http://img.blog.csdn.net/20170721084601173?">
<meta property="og:image" content="http://img.blog.csdn.net/20170721090058551?">
<meta property="og:image" content="http://img.blog.csdn.net/20170721220210716?">
<meta property="og:image" content="http://img.blog.csdn.net/20170721220326437?">
<meta property="og:image" content="http://img.blog.csdn.net/20170721220405953?">
<meta property="og:image" content="http://img.blog.csdn.net/20170721220449192?">
<meta property="og:image" content="http://img.blog.csdn.net/20170721220537242?">
<meta property="og:image" content="http://img.blog.csdn.net/20170721221314795?">
<meta property="og:image" content="http://img.blog.csdn.net/20170721221458536?">
<meta property="og:image" content="http://img.blog.csdn.net/20170721222051208?">
<meta property="og:image" content="http://img.blog.csdn.net/20170721222446843?">
<meta property="og:updated_time" content="2018-03-18T06:08:24.631Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="台湾大学林轩田机器学习技法课程学习笔记9 -- Decision Tree">
<meta name="twitter:image" content="http://img.blog.csdn.net/20170719082956412?imageView/2/w/500/q/100">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: 'ZFJHIGA2DV',
      apiKey: 'e3baeea7f059baffe169cc0eec8adacf',
      indexName: 'redstonewillblog',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键词进行搜索","hits_empty":"找不到关于 ${query} 的文章","hits_stats":"共找到 ${hits} 篇文章，耗时${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://redstonewill.github.io/2018/03/18/26/"/>





  <title>台湾大学林轩田机器学习技法课程学习笔记9 -- Decision Tree | 红色石头的机器学习之路</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
	
	<a href="https://github.com/RedstoneWill" class="github-corner" aria-label="View source on Github"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
	
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">红色石头的机器学习之路</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">公众号ID：redstonewill</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-sitemap">
          <a href="/sitemap.xml" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />
            
            站点地图
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  
  <div class="algolia-popup popup search-popup">
    <div class="algolia-search">
      <div class="algolia-search-input-icon">
        <i class="fa fa-search"></i>
      </div>
      <div class="algolia-search-input" id="algolia-search-input"></div>
    </div>

    <div class="algolia-results">
      <div id="algolia-stats"></div>
      <div id="algolia-hits"></div>
      <div id="algolia-pagination" class="algolia-pagination"></div>
    </div>

    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
  </div>




    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://redstonewill.github.io/2018/03/18/26/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="红色石头">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/blog-logo.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="红色石头的机器学习之路">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">台湾大学林轩田机器学习技法课程学习笔记9 -- Decision Tree</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-03-18T14:06:39+08:00">
                2018-03-18
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/机器学习/" itemprop="url" rel="index">
                    <span itemprop="name">机器学习</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/机器学习/林轩田机器学习技法/" itemprop="url" rel="index">
                    <span itemprop="name">林轩田机器学习技法</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2018/03/18/26/" class="leancloud_visitors" data-flag-title="台湾大学林轩田机器学习技法课程学习笔记9 -- Decision Tree">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3,805
                </span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="http://img.blog.csdn.net/20170719082956412?imageView/2/w/500/q/100" alt="这里写图片描述"><br><a id="more"></a></p>
<blockquote>
<p>我的CSDN博客地址：<a href="http://blog.csdn.net/red_stone1" target="_blank" rel="noopener">红色石头的专栏</a><br>我的知乎主页：<a href="https://www.zhihu.com/people/red_stone_wl" target="_blank" rel="noopener">红色石头</a><br>我的微博：<a href="https://weibo.com/6479023696/profile?topnav=1&amp;wvr=6&amp;is_all=1" target="_blank" rel="noopener">RedstoneWill的微博</a><br>我的GitHub：<a href="https://github.com/RedstoneWill" target="_blank" rel="noopener">RedstoneWill的GitHub</a><br>我的微信公众号：红色石头的机器学习之路（ID：redstonewill）<br>欢迎大家关注我！共同学习，共同进步！</p>
</blockquote>
<p>上节课我们主要介绍了Adaptive Boosting。AdaBoost演算法通过调整每笔资料的权重，得到不同的hypotheses，然后将不同的hypothesis乘以不同的系数$\alpha$进行线性组合。这种演算法的优点是，即使底层的演算法g不是特别好（只要比乱选好点），经过多次迭代后算法模型会越来越好，起到了boost提升的效果。本节课将在此基础上介绍一种新的aggregation算法：决策树（Decision Tree）。</p>
<h3 id="Decision-Tree-Hypothesis"><a href="#Decision-Tree-Hypothesis" class="headerlink" title="Decision Tree Hypothesis"></a>Decision Tree Hypothesis</h3><p>从第7节课开始，我们就一直在介绍aggregation model。aggregation的核心就是将许多可供选择使用的比较好的hypothesis融合起来，利用集体的智慧组合成G，使其得到更好的机器学习预测模型。下面，我们先来看看已经介绍过的aggregation type有哪些。</p>
<p><img src="http://img.blog.csdn.net/20170719082956412?" alt="这里写图片描述"></p>
<p>aggregation type有三种：uniform，non-uniform，conditional。它有两种情况，一种是所有的g是已知的，即blending。对应的三种类型分别是voting/averaging，linear和stacking。另外一种情况是所有g未知，只能通过手上的资料重构g，即learning。其中uniform和non-uniform分别对应的是Bagging和AdaBoost算法，而conditional对应的就是我们本节课将要介绍的Decision Tree算法。</p>
<p>决策树（Decision Tree）模型是一种传统的算法，它的处理方式与人类思维十分相似。例如下面这个例子，对下班时间、约会情况、提交截止时间这些条件进行判断，从而决定是否要进行在线课程测试。如下图所示，整个流程类似一个树状结构。</p>
<p><img src="http://img.blog.csdn.net/20170719084744044?" alt="这里写图片描述"></p>
<p>图中每个条件和选择都决定了最终的结果，Y or N。蓝色的圆圈表示树的叶子，即最终的决定。</p>
<p>把这种树状结构对应到一个hypothesis G(x)中，G(x)的表达式为：</p>
<p>$$G(x)=\sum_{t=1}^Tq_t(x)\cdot g_t(x)$$</p>
<p>G(x)由许多$g_t(x)$组成，即aggregation的做法。每个$g_t(x)$就代表上图中的蓝色圆圈（树的叶子）。这里的$g_t(x)$是常数，因为是处理简单的classification问题。我们把这些$g_t(x)$称为base hypothesis。$q_t(x)$表示每个$g_t(x)$成立的条件，代表上图中橘色箭头的部分。不同的$g_t(x)$对应于不同的$q_t(x)$，即从树的根部到顶端叶子的路径不同。图中中的菱形代表每个简单的节点。所以，这些base hypothesis和conditions就构成了整个G(x)的形式，就像一棵树一样，从根部到顶端所有的叶子都安全映射到上述公式上去了。</p>
<p><img src="http://img.blog.csdn.net/20170719103654190?" alt="这里写图片描述"></p>
<p>决策树实际上就是在模仿人类做决策的过程。一直以来，决策树的应用十分广泛而且分类预测效果都很不错，而它在数学上的理论完备性不充分，倒也不必在意。</p>
<p>如果从另外一个方面来看决策树的形式，不同于上述G(x)的公式，我们可以利用条件分支的思想，将整体G(x)分成若干个$G_c(x)$，也就是把整个大树分成若干个小树，如下所示：</p>
<p>$$G(x)=\sum_{c=1}^C[b(x)=c]\cdot G_c(x)$$</p>
<p>上式中，G(x)表示完整的大树，即full-tree hypothesis，b(x)表示每个分支条件，即branching criteria，$G_c(x)$表示第c个分支下的子树，即sub-tree。这种结构被称为递归型的数据结构，即将大树分割成不同的小树，再将小树继续分割成更小的子树。所以，决策树可以分为两部分：root和sub-trees。</p>
<p><img src="http://img.blog.csdn.net/20170719103835724?" alt="这里写图片描述"></p>
<p>在详细推导决策树算法之前，我们先来看一看它的优点和缺点。首先，decision tree的优点有：</p>
<ul>
<li><p><strong>模型直观，便于理解，应用广泛</strong></p>
</li>
<li><p><strong>算法简单，容易实现</strong></p>
</li>
<li><p><strong>训练和预测时，效率较高</strong></p>
</li>
</ul>
<p>然而，decision tree也有相应的缺点：</p>
<ul>
<li><p><strong>缺少足够的理论支持</strong></p>
</li>
<li><p><strong>如何选择合适的树结构对初学者来说比较困惑</strong></p>
</li>
<li><p><strong>决策树代表性的演算法比较少</strong></p>
</li>
</ul>
<p><img src="http://img.blog.csdn.net/20170719155104812?" alt="这里写图片描述"></p>
<h3 id="Decision-Tree-Algorithm"><a href="#Decision-Tree-Algorithm" class="headerlink" title="Decision Tree Algorithm"></a>Decision Tree Algorithm</h3><p>我们可以用递归形式将decision tree表示出来，它的基本的算法可以写成：</p>
<p><img src="http://img.blog.csdn.net/20170720073120706?" alt="这里写图片描述"></p>
<p>这个Basic Decision Tree Algorithm的流程可以分成四个部分，首先学习设定划分不同分支的标准和条件是什么；接着将整体数据集D根据分支个数C和条件，划为不同分支下的子集Dc；然后对每个分支下的Dc进行训练，得到相应的机器学习模型Gc；最后将所有分支下的Gc合并到一起，组成大矩G(x)。但值得注意的是，这种递归的形式需要终止条件，否则程序将一直进行下去。当满足递归的终止条件之后，将会返回基本的hypothesis $g_t(x)$。</p>
<p><img src="http://img.blog.csdn.net/20170720074057776?" alt="这里写图片描述"></p>
<p>所以，决策树的基本演算法包含了四个选择：</p>
<ul>
<li><p><strong>分支个数（number of branches）</strong></p>
</li>
<li><p><strong>分支条件（branching criteria）</strong></p>
</li>
<li><p><strong>终止条件（termination criteria）</strong></p>
</li>
<li><p><strong>基本算法（base hypothesis）</strong></p>
</li>
</ul>
<p>下面我们来介绍一种常用的决策树模型算法，叫做Classification and Regression Tree(C&amp;RT)。C&amp;RT算法有两个简单的设定，首先，分支的个数C=2，即二叉树（binary tree）的数据结构；然后，每个分支最后的$g_t(x)$（数的叶子）是一个常数。按照最小化$E_{in}$的目标，对于binary/multiclass classification(0/1 error)问题，看正类和负类哪个更多，$g_t(x)$取所占比例最多的那一类$y_n$；对于regression(squared error)问题，$g_t(x)$则取所有$y_n$的平均值。</p>
<p><img src="http://img.blog.csdn.net/20170720081326313?" alt="这里写图片描述"></p>
<p>对于决策树的基本演算法流程，C&amp;RT还有一些简单的设定。首先，C&amp;RT分支个数C=2，一般采用上节课介绍过的decision stump的方法进行数据切割。也就是每次在一个维度上，只对一个特征feature将数据一分为二，左子树和右子树，分别代表不同的类别。然而，怎么切割才能让数据划分得最好呢（error最小）？C&amp;RT中使用纯净度purifying这个概念来选择最好的decision stump。purifying的核心思想就是每次切割都尽可能让左子树和右子树中同类样本占得比例最大或者$y_n$都很接近（regression），即错误率最小。比如说classifiacation问题中，如果左子树全是正样本，右子树全是负样本，那么它的纯净度就很大，说明该分支效果很好。</p>
<p><img src="http://img.blog.csdn.net/20170720083357302?" alt="这里写图片描述"></p>
<p>根据C&amp;RT中purifying的思想，我们得到选择合适的分支条件b(x)的表达式如上所示。最好的decision stump重点包含两个方面：一个是刚刚介绍的分支纯净度purifying，purifying越大越好，而这里使用purifying相反的概念impurity，则impurity越小越好；另外一个是左右分支纯净度所占的权重，权重大小由该分支的数据量决定，分支包含的样本个数越多，则所占权重越大，分支包含的样本个数越少，则所占权重越小。上式中的$|D_c\ with\ h|$代表了分支c所占的权重。这里b(x)类似于error function（这也是为什么使用impurity代替purifying的原因），选择最好的decision stump，让所有分支的不纯度最小化，使b(x)越小越好。</p>
<p>不纯度Impurity如何用函数的形式量化？一种简单的方法就是类比于$E_{in}$，看预测值与真实值的误差是多少。对于regression问题，它的impurity可表示为：</p>
<p>$$impurity(D)=\frac1N\sum_{n=1}^N(y_n-\overline{y})^2$$</p>
<p>其中，$\overline{y}$表示对应分支下所有$y_n$的均值。</p>
<p>对应classification问题，它的impurity可表示为：</p>
<p>$$impurity(D)=\frac1N\sum_{n=1}^N[y_n\neq y^*]$$</p>
<p>其中，$y^*$表示对应分支下所占比例最大的那一类。</p>
<p><img src="http://img.blog.csdn.net/20170720090259338?" alt="这里写图片描述"></p>
<p>以上这些impurity是基于原来的regression error和classification error直接推导的。进一步来看classification的impurity functions，如果某分支条件下，让其中一个分支纯度最大，那么就选择对应的decision stump，即得到的classification error为：</p>
<p>$$1-max_{1\leq k\leq K}\frac{\sum_{n=1}^N[y_n=k]}{N}$$</p>
<p>其中，K为分支个数。</p>
<p>上面这个式子只考虑纯度最大的那个分支，更好的做法是将所有分支的纯度都考虑并计算在内，用基尼指数（Gini index）表示：</p>
<p>$$1-\sum_{k=1}^K(\frac{\sum_{n=1}^N[y_n=k]}{N})^2$$</p>
<p>Gini index的优点是将所有的class在数据集中的分布状况和所占比例全都考虑了，这样让decision stump的选择更加准确。</p>
<p><img src="http://img.blog.csdn.net/20170720112908397?" alt="这里写图片描述"></p>
<p>对于决策树C&amp;RT算法，通常来说，上面介绍的各种impurity functions中，Gini index更适合求解classification问题，而regression error更适合求解regression问题。</p>
<p>C&amp;RT算法迭代终止条件有两种情况，第一种情况是当前各个分支下包含的所有样本$y_n$都是同类的，即不纯度impurity为0，表示该分支已经达到了最佳分类程度。第二种情况是该特征下所有的$x_n$相同，无法对其进行区分，表示没有decision stumps。遇到这两种情况，C&amp;RT算法就会停止迭代。</p>
<p><img src="http://img.blog.csdn.net/20170720135537933?" alt="这里写图片描述"></p>
<p>所以，C&amp;RT算法遇到迭代终止条件后就成为完全长成树（fully-grown tree）。它每次分支为二，是二叉树结构，采用purify来选择最佳的decision stump来划分，最终得到的叶子（$g_t(x)$）是常数。</p>
<h3 id="Decision-Tree-Heuristics-in-C-amp-RT"><a href="#Decision-Tree-Heuristics-in-C-amp-RT" class="headerlink" title="Decision Tree Heuristics in C&amp;RT"></a>Decision Tree Heuristics in C&amp;RT</h3><p>现在我们已经知道了C&amp;RT算法的基本流程：</p>
<p><img src="http://img.blog.csdn.net/20170720152355327?" alt="这里写图片描述"></p>
<p>可以看到C&amp;RT算法在处理binary classification和regression问题时非常简单实用，而且，处理muti-class classification问题也十分容易。</p>
<p>考虑这样一个问题，有N个样本，如果我们每次只取一个样本点作为分支，那么在经过N-1次分支之后，所有的样本点都能完全分类正确。最终每片叶子上只有一个样本，有N片叶子，即必然能保证$E_{in}=0$。这样看似是完美的分割，但是不可避免地造成VC Dimension无限大，造成模型复杂度增加，从而出现过拟合现象。为了避免overfit，我们需要在C&amp;RT算法中引入正则化，来控制整个模型的复杂度。</p>
<p>考虑到避免模型过于复杂的方法是减少叶子（$g_t(x)$）的数量，那么可以令regularizer就为决策树中叶子的总数，记为$\Omega(G)$。正则化的目的是尽可能减少$\Omega(G)$的值。这样，regularized decision tree的形式就可以表示成：</p>
<p>$$argmin_{(all\ possible\ G)}\ E_{in}(G)+\lambda\Omega(G)$$</p>
<p>我们把这种regularized decision tree称为pruned decision tree。pruned是修剪的意思，通过regularization来修剪决策树，去掉多余的叶子，更简洁化，从而达到避免过拟合的效果。</p>
<p>那么如何确定修剪多少叶子，修剪哪些叶子呢？假设由C&amp;RT算法得到一棵完全长成树（fully-grown tree），总共10片叶子。首先分别减去其中一片叶子，剩下9片，将这10种情况比较，取$E_{in}$最小的那个模型；然后再从9片叶子的模型中分别减去一片，剩下8片，将这9种情况比较，取$E_{in}$最小的那个模型。以此类推，继续修建叶子。这样，最终得到包含不同叶子的几种模型，将这几个使用regularized decision tree的error function来进行选择，确定包含几片叶子的模型误差最小，就选择该模型。另外，参数$\lambda$可以通过validation来确定最佳值。</p>
<p><img src="http://img.blog.csdn.net/20170721083658001?" alt="这里写图片描述"></p>
<p>我们一直讨论决策树上的叶子（features）都是numerical features，而实际应用中，决策树的特征值可能不是数字量，而是类别（categorical features）。对于numerical features，我们直接使用decision stump进行数值切割；而对于categorical features，我们仍然可以使用decision subset，对不同类别进行“左”和“右”，即是与不是（0和1）的划分。numerical features和categorical features的具体区别如下图所示：</p>
<p><img src="http://img.blog.csdn.net/20170721084601173?" alt="这里写图片描述"></p>
<p>在决策树中预测中，还会遇到一种问题，就是当某些特征缺失的时候，没有办法进行切割和分支选择。一种常用的方法就是surrogate branch，即寻找与该特征相似的替代feature。如何确定是相似的feature呢？做法是在决策树训练的时候，找出与该特征相似的feature，如果替代的feature与原feature切割的方式和结果是类似的，那么就表明二者是相似的，就把该替代的feature也存储下来。当预测时遇到原feature缺失的情况，就用替代feature进行分支判断和选择。</p>
<p><img src="http://img.blog.csdn.net/20170721090058551?" alt="这里写图片描述"></p>
<h3 id="Decision-Tree-in-Action"><a href="#Decision-Tree-in-Action" class="headerlink" title="Decision Tree in Action"></a>Decision Tree in Action</h3><p>最后我们来举个例子看看C&amp;RT算法究竟是如何进行计算的。例如下图二维平面上分布着许多正负样本，我们使用C&amp;RT算法来对其进行决策树的分类。</p>
<p><img src="http://img.blog.csdn.net/20170721220210716?" alt="这里写图片描述"></p>
<p>第一步：</p>
<p><img src="http://img.blog.csdn.net/20170721220326437?" alt="这里写图片描述"></p>
<p>第二步：</p>
<p><img src="http://img.blog.csdn.net/20170721220405953?" alt="这里写图片描述"></p>
<p>第三步：</p>
<p><img src="http://img.blog.csdn.net/20170721220449192?" alt="这里写图片描述"></p>
<p>第四步：</p>
<p><img src="http://img.blog.csdn.net/20170721220537242?" alt="这里写图片描述"></p>
<p>在进行第四步切割之后，我们发现每个分支都已经非常纯净了，没有办法继续往下切割。此时表明已经满足了迭代终止条件，这时候就可以回传base hypothesis，构成sub tree，然后每个sub tree再往上整合形成tree，最后形成我们需要的完全决策树。如果将边界添加上去，可得到下图：</p>
<p><img src="http://img.blog.csdn.net/20170721221314795?" alt="这里写图片描述"></p>
<p>得到C&amp;RT算法的切割方式之后，我们与AdaBoost-Stump算法进行比较：</p>
<p><img src="http://img.blog.csdn.net/20170721221458536?" alt="这里写图片描述"></p>
<p>我们之前就介绍过，AdaBoost-Stump算法的切割线是横跨整个平面的；而C&amp;RT算法的切割线是基于某个条件的，所以一般不会横跨整个平面。比较起来，虽然C&amp;RT和AdaBoost-Stump都采用decision stump方式进行切割，但是二者在细节上还是有所区别。</p>
<p>再看一个数据集分布比较复杂的例子，C&amp;RT和AdaBoost-Stump的切割方式对比效果如下图所示：</p>
<p><img src="http://img.blog.csdn.net/20170721222051208?" alt="这里写图片描述"></p>
<p>通常来说，由于C&amp;RT是基于条件进行切割的，所以C&amp;RT比AdaBoost-Stump分类切割更有效率。总结一下，C&amp;RT决策树有以下特点：</p>
<p><img src="http://img.blog.csdn.net/20170721222446843?" alt="这里写图片描述"></p>
<h3 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h3><p>本节课主要介绍了Decision Tree。首先将decision tree hypothesis对应到不同分支下的矩$g_t(x)$。然后再介绍决策树算法是如何通过递归的形式建立起来。接着详细研究了决策树C&amp;RT算法对应的数学模型和算法架构流程。最后通过一个实际的例子来演示决策树C&amp;RT算法是如何一步一步进行分类的。</p>
<p><strong><em>注明：</em></strong></p>
<p>文章中所有的图片均来自台湾大学林轩田《机器学习技法》课程</p>

      
    </div>
    
    
    
	
    
      <div>
        <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/wechat-qcode.jpg" alt="红色石头 wechat" style="width: 200px; max-width: 100%;"/>
    <div>欢迎您扫一扫上面的微信公众号，了解更多AI资源！</div>
</div>

      </div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="红色石头 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="红色石头 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    红色石头
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://redstonewill.github.io/2018/03/18/26/" title="台湾大学林轩田机器学习技法课程学习笔记9 -- Decision Tree">https://redstonewill.github.io/2018/03/18/26/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/机器学习/" rel="tag"><i class="fa fa-tag"></i> 机器学习</a>
          
            <a href="/tags/林轩田/" rel="tag"><i class="fa fa-tag"></i> 林轩田</a>
          
            <a href="/tags/笔记/" rel="tag"><i class="fa fa-tag"></i> 笔记</a>
          
            <a href="/tags/技法/" rel="tag"><i class="fa fa-tag"></i> 技法</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/03/18/25/" rel="next" title="台湾大学林轩田机器学习技法课程学习笔记8 -- Adaptive Boosting">
                <i class="fa fa-chevron-left"></i> 台湾大学林轩田机器学习技法课程学习笔记8 -- Adaptive Boosting
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/03/18/27/" rel="prev" title="台湾大学林轩田机器学习技法课程学习笔记10 -- Random Forest">
                台湾大学林轩田机器学习技法课程学习笔记10 -- Random Forest <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- Go to www.addthis.com/dashboard to customize your tools -->
<div class="addthis_inline_share_toolbox">
  <script type = "text/javascript" src = "//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5aaa217593e0eff1" async = "async" ></script>
</div>

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNDg0MS8xMTM3OA=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/blog-logo.jpg"
                alt="红色石头" />
            
              <p class="site-author-name" itemprop="name">红色石头</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/RedstoneWill" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://blog.csdn.net/red_stone1" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-contao"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/red_stone_wl/activities" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-globe"></i>知乎</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://weibo.com/redstonewill" target="_blank" title="微博">
                      
                        <i class="fa fa-fw fa-weibo"></i>微博</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:redstonewill@hotmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#Decision-Tree-Hypothesis"><span class="nav-number">1.</span> <span class="nav-text">Decision Tree Hypothesis</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Decision-Tree-Algorithm"><span class="nav-number">2.</span> <span class="nav-text">Decision Tree Algorithm</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Decision-Tree-Heuristics-in-C-amp-RT"><span class="nav-number">3.</span> <span class="nav-text">Decision Tree Heuristics in C&amp;RT</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Decision-Tree-in-Action"><span class="nav-number">4.</span> <span class="nav-text">Decision Tree in Action</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Summary"><span class="nav-number">5.</span> <span class="nav-text">Summary</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">红色石头</span>

  
</div>

<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_pv"></span>
</span>
</div>









<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共150.1k字</span>
</div>
        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  




  
  
  
  <link rel="stylesheet" href="/lib/algolia-instant-search/instantsearch.min.css">

  
  
  <script src="/lib/algolia-instant-search/instantsearch.min.js"></script>
  

  <script src="/js/src/algolia-search.js?v=5.1.4"></script>



  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("GPinP9RLLAEN4cQw3GyGH1i6-gzGzoHsz", "P23pTYCEXWROAMFxuaSGYGIa");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
